<template>
  <div class="addCar">
    <van-nav-bar
      title="添加爱车"
      fixed
      safe-area-inset-top
      @click-left="onClickLeft"
    />
    <div class="box">
      <div class="title">输入车牌</div>
      <div class="number">
        <div
          v-for="(v, i) in keyboardList"
          :key="i"
          class="number_item"
          :class="{
            active: index == i,
            green: i == keyboardList.length - 1 && !v && index != i,
          }"
          @click="handleClickKey(i)"
        >
          {{ v }}
        </div>
        <!-- <div class="number_item number_item_D" :class="{ green: isNewEnergy }" @click="isNewEnergy = !isNewEnergy">
          新能源
        </div> -->
      </div>
    </div>
    <div class="check-box">
      <van-checkbox v-model="checked"
        >已阅读并同意《用户信息授权说明》</van-checkbox
      >
    </div>
    <div class="form">
      <van-form @submit="onSubmit">
        <van-field
          v-model="field.ownerName"
          label="车主姓名"
          placeholder="请输入"
        />
        <van-field
          v-model="field.ownerPhone"
          label="车主手机号"
          type="digit"
          placeholder="请输入"
        />
        <van-field
          v-model="field.brand"
          label="车辆品牌"
          placeholder="请输入"
        />
        <van-field
          v-model="field.mileage"
          label="行驶里程数"
          type="digit"
          placeholder="请输入"
        />
        <van-field
          v-model="field.purchasingDate"
          label="购买时间"
          placeholder="请选择"
          readonly
          clickable
          @click="showTime = true"
        />
        <van-popup v-model="showTime" position="bottom">
          <van-datetime-picker
            type="date"
            @confirm="selectTime"
            @cancel="showTime = false"
          />
        </van-popup>
        <div class="submit">
          <van-button round block type="info" native-type="submit"
            >保存</van-button
          >
        </div>
      </van-form>
    </div>
    <vnp-keyboard
      v-model="val"
      :show.sync="show"
      :keybordType="type"
      @del="del"
    ></vnp-keyboard>
  </div>
</template>

<script>
import api from "@/api/api";
import keyboard from "@/components/number-plate/keybord.vue";
import { formatTime } from "@/utils/common";
import { Toast } from "vant";
import { mapGetters } from "vuex";
export default {
  components: {
    "vnp-keyboard": keyboard,
  },
  props: {},
  data() {
    return {
      val: "",
      keyboardList: ["浙", "", "", "", "", "", "", ""],
      show: false,
      index: -1,
      type: "cn",
      isNewEnergy: false,
      checked: false,
      showTime: false,
      field: {
        ownerName: "",
        ownerPhone: "",
        brand: "",
        mileage: "",
        purchasingDate: "",
      },
      carInfo: {},
      pageType: "add",
    };
  },
  watch: {
    val(newVal) {
      this.keyboardList[this.index] = newVal;
      if (this.index < this.keyboardList.length - 1) {
        this.index++;
        this.type = "en";
      } else {
        this.index = -1;
        this.show = false;
      }
    },
    show(newVal) {
      if (!newVal) {
        this.index = -1;
      }
    },
  },
  computed: {
    ...mapGetters(["userData", "carList"]),
  },
  methods: {
    onClickLeft() {
      this.$router.back();
    },
    handleClickKey(index) {
      if (index == 0) {
        this.index = index;
        this.show = true;
        this.type = "cn";
        return;
      } else {
        if (this.keyboardList[index - 1] == "") {
          return;
        } else {
          this.index = index;
          this.type = "en";
          this.show = true;
        }
      }
    },
    del() {
      // console.log(this.index, this.keyboardList[this.index]);

      if (this.index > 0) {
        if (this.keyboardList[this.index]) {
          this.keyboardList.splice(this.index, 1, "");
        } else {
          this.index--;
          if (this.index == 0) {
            this.type = "cn";
          }
          this.keyboardList.splice(this.index, 1, "");
        }
      } else if (this.index == 0) {
        this.keyboardList.splice(this.index, 1, "");
      }
    },
    selectTime(val) {
      this.field.purchasingDate = formatTime(val);
      this.showTime = false;
    },
    onSubmit() {
      if (this.pageType == "add") {
        this.addCar();
      } else {
        this.editCar();
      }
    },
    async addCar() {
      let plate = this.keyboardList.join("");
      if (plate.trim().length < 7) {
        Toast("请输入完整车牌号");
        return;
      }
      if (!this.field.brand) {
        Toast("请输入车辆品牌");
        return;
      }
      let params = {
        ...this.field,
        plateNumber: plate,
      };
      await api.addCar(params);
      let res = await api.getCarList({});
      this.$store.commit("user/SET_CAR", res.data);
      Toast({
        message: "添加成功",
        duration: 1200,
      });
      setTimeout(() => {
        this.$router.back();
      }, 1200);
    },
    async editCar() {
      let plate = this.keyboardList.join("");
      if (plate.trim().length < 7) {
        Toast("请输入完整车牌号");
        return;
      }
      if (!this.field.brand) {
        Toast("请输入车辆品牌");
        return;
      }
      let params = {
        ...this.field,
        plateNumber: plate,
      };
      // console.log(params);

      await api.updateCarInfo(params);
      let res = await api.getCarList({});
      this.$store.commit("user/SET_CAR", res.data);
      Toast({
        message: "编辑成功",
        duration: 1200,
      });
      setTimeout(() => {
        this.$router.back();
      }, 1200);
    },
  },
  created() {},
  mounted() {
    this.field.ownerName = this.userData.userName;
    this.field.ownerPhone = this.userData.phone;
    let id = this.$route.query.id ?? null;
    this.pageType = this.$route.query.type ?? this.pageType;
    if (this.pageType == "edit") {
      this.carInfo = this.carList.find((v) => v.id == id);
      (this.field.brand = this.carInfo.brand),
        (this.field.mileage = this.carInfo.mileage);
      this.field.id = id;
      this.field.purchasingDate = this.carInfo.purchasingDate;
      this.keyboardList = this.carInfo.plateNumber
        .split("")
        .map((item) => item.trim());
      if (this.keyboardList.length == 7) {
        this.keyboardList.push("");
      }
    }
  },
};
</script>
<style lang="less" scoped>
.addCar {
  min-height: 100vh;
  background: url("https://zxcxappimg.oss-cn-hangzhou.aliyuncs.com//zxcxmall/2025/05/29/44dea588672142d48f873df92c7b625e.jpg")
    no-repeat;
  background-size: cover;
  background-attachment: local;
  background-position: top center;
  box-sizing: border-box;
  padding: 150px 60px 60px 60px;
  position: relative;

  .box {
    width: 100%;
    padding: 55px 30px 35px 30px;
    background: #fff;
    margin-top: 80px;
    border-radius: 15px;

    .title {
      font-size: 44px;
      color: #000;
      margin-bottom: 50px;
      letter-spacing: 4px;
    }

    .number {
      display: flex;
      justify-content: space-between;
      align-items: center;

      &_item {
        width: calc(100% / 8 - 10px);
        height: 160px;
        background: #f5f5f5;
        border-radius: 10px;
        color: #000;
        font-weight: bold;
        text-align: center;
        line-height: 160px;
        font-size: 39px;
      }

      .green {
        background: #d9feec;
        border: 3px dashed #7fd5b2;
        // line-height: 160px;
        text-align: center;
        // font-size: 35px;
        color: #56d3a1;
        // padding: 0 5px;
      }

      .number_item_D {
        font-size: 35px;
        padding: 0 5px;
      }

      .active {
        background: #fee9f0;
      }
    }
  }

  .check-box {
    margin-top: 30px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 30px;
    font-size: 30px;

    /deep/.van-checkbox__icon {
      font-size: 36px;
      // border: 1px solid #828282;
      display: flex;
      align-items: center;
    }
  }

  .form {
    margin-top: 30px;

    /deep/ .van-cell {
      background: transparent;

      .van-field__label {
        color: #000 !important;
      }

      .van-field__control {
        background-color: #fff;
        border-radius: 20px;
        box-sizing: border-box;
        padding: 0 20px;
        border: 3px solid #b5c0cc;
        font-size: 30px;
      }

      input::placeholder {
        color: #000;
        font-size: 30px;
      }
    }

    .submit {
      margin-top: 150px;
      width: 100%;
      padding: 0 100px;
    }
  }

  /deep/ .van-nav-bar__left {
    .van-icon {
      color: #303030;
      font-weight: bold;
    }
  }

  /deep/ .van-overlay {
    background: transparent !important;
  }
}
</style>
